package com.xy.tool.minio.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;

/**
 * @Author wwj
 * @Date 2021/1/28
 */
@Component
public class UrlUtil {

    private static String ip;

    @Value("${localhostIP}")
    public void setIp(String ip) {
        UrlUtil.ip = ip;
    }

    public static String GetCallback(String minFileName, HttpServletRequest request) {
        String serverPath = GetServerUrl(request);
        String hostAddress = CurUserHostAddress(null);
        try {
            String query = "?type=track&fileName=" + URLEncoder.encode(minFileName, java.nio.charset.StandardCharsets.UTF_8.toString()) + "&userAddress=" + URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString());
//            String query = "?type=track&fileName=" + minFileName + "&userAddress=" + URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString());

            return serverPath + "/only/index" + query;
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    public static String GetServerUrl(HttpServletRequest request) {
        //todo
//        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        return request.getScheme() + "://" + ip + ":" + request.getServerPort() + request.getContextPath();
//        return request.getScheme() + "://" + "192.168.1.1" + ":" + request.getServerPort() + request.getContextPath();
    }

    public static String CurUserHostAddress(String userAddress) {
        if (userAddress == null) {
            try {
//               userAddress = InetAddress.getLocalHost().getHostAddress();
                userAddress = ip;
//                userAddress = "192.168.1.1";
            } catch (Exception ex) {
                userAddress = "";
            }
        }

        return userAddress.replaceAll("[^0-9a-zA-Z.=]", "_");
    }

}
